/*
 * @Author: 邵东亮 1762111402@qq.com
 * @Date: 2024-12-14 15:58:33
 * @LastEditors: 邵东亮 1762111402@qq.com
 * @LastEditTime: 2024-12-16 10:36:47
 * @Description:
 * @FilePath: \express\bigData_server\controller\loginController.js
 */
const pool = require("../config/db"); //引入数据库连接池
const userService = require("../service/userService"); //引入用户服务
const svgCaptcha = require("svg-captcha"); //引入验证码模块
const JWT = require("../util/token"); //引入token模块
const bcrypt = require("bcrypt"); //引入加密模块
exports.login = function (req, res) {
  let { username, password } = req.body;
  console.log(username, password);

  let session_captcha = req.session.captcha; // 获取session中的验证码
  console.log("session_captcha:", session_captcha);

  if (!session_captcha) {
    return res.json({ msg: "验证码已过期" });
  }
  if (session_captcha === req.body.captcha.toLowerCase()) {
    // 验证码正确，进行登录操作
    // 登录成功，签发一个token并返回给前端
    // let password = req.body.password;
    console.log(password);
    pool.query(userService.getPwdbyUserName, username, (err, data) => {
      if (err) {
        return res.json({
          msg: "数据库查询失败",
          code: 201,
        });
      }
      if (data.length === 0) {
        return res.json({
          msg: "用户不存在",
          code: 201,
        });
      }

      bcrypt.compare(password, data[0].password, (err, result) => {
        if (err) {
          return res.json({
            msg: "密码错误1",
            code: 201,
          });
        } else {
          if (result) {
            let token =
              "Bearer " +
              JWT.createToken({
                username,
                isLogin: true,
              });

            return res.json({
              msg: "登录成功",
              code: 200,
              data: { token },
            });
          } else {
            return res.json({
              msg: "密码错误",
              code: 201,
              data: null,
            });
          }
        }
      });
    });
  } else {
    return res.json({
      msg: "验证码错误",
      code: 201,
      data: null,
    });
  }
};

exports.captcha = function (req, res) {
  // console.log("验证码", req.body);

  let options = {
    size: 4, // 4个字母
    noise: 1, // 干扰线2条
    color: true, // 文字颜色
    background: "#666", // 背景颜色
    width: 90,
    height: 32,
    fontSize: 34,
    ignoreChars: "0oO1ilI",
    // 数字的时候，设置下面属性。最大，最小，加或者减
    // mathMin: 1,
    // mathMax: 30,
    // mathOperator: "+",
  };
  let captcha = svgCaptcha.create(options); //字母和数字随机验证码
  // let captcha = svgCaptcha.createMathExpr(options) //数字算数随机验证码
  let { text, data } = captcha;
  req.session.captcha = text.toLowerCase();
  console.log(req.session.captcha);

  // req.session.cookie.maxAge = 60000 * 5; // 设置 session 过期时间为 1 分钟
  // console.log("验证码", req.session.captcha);

  // res.type("svg");
  res.status(200).json({ data: data, msg: text, code: 200 });
};
